﻿using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.Mvc;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Atacadao.DB.DataAnnotation;
using Atacadao.Comum.DataAnnotation;


public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
{
    
	private string RecuperarTemplate(System.Collections.Generic.IEnumerable<System.Attribute> attributes)
	{
        var retorno = attributes.OfType<ITemplate>().Select(f => f.Nome).LastOrDefault();

		return retorno;
	}

	protected override System.Collections.Generic.IEnumerable<System.Attribute> FilterAttributes(System.Type containerType, System.ComponentModel.PropertyDescriptor propertyDescriptor, System.Collections.Generic.IEnumerable<System.Attribute> attributes)
	{
		return base.FilterAttributes(containerType, propertyDescriptor, attributes);
	}

	protected override ModelMetadata CreateMetadata(System.Collections.Generic.IEnumerable<System.Attribute> attributes, System.Type containerType, System.Func<object> modelAccessor, System.Type modelType, string propertyName)
	{


		DataAnnotationsModelMetadata result = (DataAnnotationsModelMetadata)base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

		string templateName = string.Empty;

		templateName = RecuperarTemplate(attributes);

		if ((string.IsNullOrEmpty(templateName)))
			templateName = result.TemplateHint;

		return new CustomModelMetada(this, containerType, modelAccessor, modelType, propertyName, attributes.OfType<DisplayColumnAttribute>().FirstOrDefault(), attributes) {
			TemplateHint = templateName,
			HideSurroundingHtml = result.HideSurroundingHtml,
			DataTypeName = result.DataTypeName,
			IsReadOnly = result.IsReadOnly,
			NullDisplayText = result.NullDisplayText,
			DisplayFormatString = result.DisplayFormatString,
			ConvertEmptyStringToNull = result.ConvertEmptyStringToNull,
			EditFormatString = result.EditFormatString,
			ShowForDisplay = result.ShowForDisplay,
			ShowForEdit = result.ShowForEdit,
			DisplayName = result.DisplayName
		};



	}
}